﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using NLog.Config;
using NLog.Targets;
using Widgetsphere.Autos.EFDAL;

namespace Widgetsphere.Autos.API
{
    /// <summary />
    public static class Logger
    {
        #region Class Members

        private const string _eventSource = "JobBoard Logger";
        private static readonly NLog.Logger _logger = null;

        #endregion

        #region Constructor

        static Logger()
        {
            var config = new LoggingConfiguration();

            //Fiel Target 
            var fileTarget = new FileTarget();
            fileTarget.FileName = "${basedir}/logs/${shortdate}.txt";
            fileTarget.Layout = "${level} | ${longdate}  | ${message} | ${exception:format=Message,ShortType,StackTrace}";
            fileTarget.KeepFileOpen = false;
            fileTarget.Encoding = System.Text.Encoding.ASCII;
            config.AddTarget("file", fileTarget);

            //Add File Rule
            var rule1 = new LoggingRule("*", LogLevel.Debug, fileTarget);
            config.LoggingRules.Add(rule1);

            //Console Target
            var consoleTarget = new ColoredConsoleTarget();
            config.AddTarget("console", consoleTarget);
            consoleTarget.Layout = @"${date:format=HH\:MM\:ss} ${logger} ${message}";

            //Add Console Rule
            var rule2 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
            config.LoggingRules.Add(rule2);

            LogManager.Configuration = config;

            //_logger = NLog.LogManager.GetCurrentClassLogger();
            _logger = NLog.LogManager.GetLogger("Example");
        }

        #endregion

        #region Logging

        /// <summary />
        public static void LogError(string message)
        {
            try
            {
                if (_logger != null)
                {
                    _logger.Error(message);
                    LogErrorToDb(message);
                }
            }
            catch (Exception ex)
            {
                //Do Nothing
            }
        }

        /// <summary />
        public static void LogError(Exception exception, string message)
        {
            try
            {
                if (message == null) message = string.Empty;
                if (!string.IsNullOrEmpty(message)) message += "\n";

                if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine("URL: " + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
                    if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
                        sb.AppendLine("Referrer: " + System.Web.HttpContext.Current.Request.UrlReferrer.PathAndQuery);
                    sb.AppendLine("IPAddress: " + Utilities.CallingIPAddress);
                    //sb.AppendLine("UserId: " + SessionHelper.CurrentUserId);
                    message += sb.ToString();
                }
            }
            catch (Exception ex)
            {
                //Do Nothing
            }

            try
            {
                if (_logger != null)
                {
                    _logger.Error(message + exception.ToString());
                    LogErrorToDb(message + exception.ToString());
                }

                //Only send these types of emails as errors
                if (exception is System.Web.HttpUnhandledException)
                {
                    if (exception.ToString().Contains("Invalid postback or callback argument"))
                    {
                        //Do Nothing
                    }
                    else
                    {
                        var t = exception.Message;
                        if (exception.InnerException != null)
                            t = exception.InnerException.Message;
                        if (t.Length > 100) t = t.Substring(0, 100);
                        //EmailDomain.SendErrorMail(t);
                    }
                }

            }
            catch (Exception ex)
            {
                //Do Nothing
            }
        }

        /// <summary />
        public static void LogError(Exception exception)
        {
            LogError(exception, null);
        }

        /// <summary />
        public static void LogDebug(string message)
        {
            try
            {
                if (_logger != null)
                    _logger.Debug(message);
            }
            catch (Exception ex)
            {
                //Do Nothing
            }
        }

        /// <summary />
        public static void LogInfo(string message)
        {
            try
            {
                if (_logger != null)
                    _logger.Info(message);
            }
            catch (Exception ex)
            {
                //Do Nothing
            }
        }

        /// <summary />
        public static void LogWarning(string message)
        {
            try
            {
                if (_logger != null)
                    _logger.Warn(message);
            }
            catch (Exception ex)
            {
                //Do Nothing
            }
        }

        #endregion

        #region Private

        private static void LogErrorToDb(string text)
        {
            try
            {
                //using (var context = new AutosEntities())
                //{
                //    var item = new JobPlatform.JobDomain.EFDAL.Entity.ErrorLog
                //    {
                //        Text = text,
                //    };
                //    context.AddItem(item);
                //    context.SaveChanges();
                //}
            }
            catch (Exception ex)
            {
                //Do Nothing
            }
        }

        #endregion

    }
}